package com.dzl.enterprise.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.*;
import com.dzl.enterprise.dao.WelfareEnterpriseApiGoodsMapper;
import com.dzl.enterprise.pojo.WelfareEnterprise;
import com.dzl.enterprise.pojo.WelfareEnterpriseApiGoods;
import com.dzl.enterprise.pojo.dto.WelfareEnterpriseApiOrderSaveDto;
import com.dzl.enterprise.pojo.query.WelfareEnterpriseApiGoodsQuery;
import com.dzl.enterprise.pojo.vo.WelfareEnterpriseApiGoodsBaseVo;
import com.dzl.enterprise.pojo.vo.WelfareEnterpriseApiOrderExpressVo;
import com.dzl.enterprise.pojo.vo.WelfareEnterpriseApiOrderVo;
import com.dzl.enterprise.pojo.vo.WelfareEnterpriseApiGoodsVo;
import com.dzl.enterprise.service.WelfareEnterpriseApiService;
import com.dzl.enterprise.service.WelfareEnterpriseService;
import com.dzl.goods.pojo.WelfareGoods;
import com.dzl.goods.pojo.WelfareGoodsAttr;
import com.dzl.goods.service.WelfareGoodsAttrService;
import com.dzl.goods.service.WelfareGoodsService;
import com.dzl.order.pojo.WelfareOrder;
import com.dzl.order.pojo.WelfareOrderAddress;
import com.dzl.order.pojo.WelfareOrderGoods;
import com.dzl.order.pojo.vo.WelfareOrderExpressVo;
import com.dzl.order.pojo.vo.WelfareOrderGoodsVo;
import com.dzl.order.service.WelfareOrderAddressService;
import com.dzl.order.service.WelfareOrderExpressService;
import com.dzl.order.service.WelfareOrderGoodsService;
import com.dzl.order.service.WelfareOrderService;
import com.dzl.userwx.pojo.WelfareUserWx;
import com.dzl.userwx.pojo.vo.LoginWxUserInfoVo;
import com.dzl.userwx.service.WelfareUserWxService;
import com.dzl.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * api接口服务实现类
 * @author liuguanjun
 * @date 2021-11-24 14:15:23
 */
@Slf4j
@Service
public class WelfareEnterpriseApiServiceImpl implements WelfareEnterpriseApiService {

    @Autowired
    private WelfareEnterpriseApiGoodsMapper mapper;
    @Autowired
    private WelfareGoodsService welfareGoodsService;
    @Autowired
    private WelfareGoodsAttrService welfareGoodsAttrService;
    @Autowired
    private WelfareOrderService welfareOrderService;
    @Autowired
    private WelfareOrderGoodsService welfareOrderGoodsService;
    @Autowired
    private WelfareOrderAddressService welfareOrderAddressService;
    @Autowired
    private WelfareEnterpriseService welfareEnterpriseService;
    @Autowired
    private WelfareUserWxService welfareUserWxService;
    @Autowired
    private WelfareOrderExpressService welfareOrderExpressService;

    // token保存时间（分钟）todo：pro
    private static final int TOKEN_TIMES_MINUTE = 60 * 24 * 1;

    @Override
    public String getWelfareEnterpriseApiToken(String apiId, String apiSecret) {
        WelfareEnterprise welfareEnterpriseQuery = new WelfareEnterprise();
        welfareEnterpriseQuery.setApiId(apiId);
        welfareEnterpriseQuery.setApiSecret(apiSecret);
        WelfareEnterprise welfareEnterprise = welfareEnterpriseService.selectOne(welfareEnterpriseQuery);
        if(EmptyUtils.isEmpty(welfareEnterprise)){
            throw new CommonException(1001,"此商户号不存在");
        }
        if(welfareEnterprise.getStatus()==CommonConstants.NO){
            throw new CommonException(1002,"此商户号已停用");
        }
        String token = TokenUtil.generateAccessToken("api"+welfareEnterprise.getId());
        LoginWxUserInfoVo loginWxUserInfoVo = new LoginWxUserInfoVo();
        loginWxUserInfoVo.setEnterpriseId(welfareEnterprise.getId());
        RedisUtil.set(token, JSONObject.toJSONString(loginWxUserInfoVo), 60 * TOKEN_TIMES_MINUTE);//缓存1天
        return token;
    }

    @Override
    public PageInfo<WelfareEnterpriseApiGoodsBaseVo> getWelfareEnterpriseApiGoodsListPage(WelfareEnterpriseApiGoodsQuery query) {
        PageHelper.startPage(query);
        List<WelfareEnterpriseApiGoodsVo> list = mapper.selectEnterpriseGoodsList(query);
        List<WelfareEnterpriseApiGoodsBaseVo> volist = new ArrayList<>();
        list.forEach(goodsVo->{
            WelfareEnterpriseApiGoodsBaseVo welfareEnterpriseApiGoodsVo = new WelfareEnterpriseApiGoodsBaseVo();
            goodsVo.setGoodsImg(ImageUtils.setImageSrc(goodsVo.getGoodsImg()));
            if(goodsVo.getSkuStatus()== CommonConstants.YES && goodsVo.getGoodsStatus() == CommonConstants.YES){
                goodsVo.setGoodsStatus(CommonConstants.YES);
            }else{
                goodsVo.setGoodsStatus(CommonConstants.NO);
            }
            BeanUtils.copyProperties(goodsVo,welfareEnterpriseApiGoodsVo);
            welfareEnterpriseApiGoodsVo.setGoodsCode(goodsVo.getEnterpriseId()+""+goodsVo.getSkuId());
            volist.add(welfareEnterpriseApiGoodsVo);
        });
        PageInfo<WelfareEnterpriseApiGoodsVo> page_ = new PageInfo<WelfareEnterpriseApiGoodsVo>(list);
        PageInfo<WelfareEnterpriseApiGoodsBaseVo> page = new PageInfo<WelfareEnterpriseApiGoodsBaseVo>(volist);
        page.setTotal(page_.getTotal());
        return page;
    }

    @Override
    public Integer saveWelfareEnterpriseApiOrder(WelfareEnterpriseApiOrderSaveDto welfareEnterpriseApiOrderSaveDto) {
        //查询商品及商品sku对象
        WelfareGoodsAttr welfareGoodsAttr = welfareGoodsAttrService.selectByPrimaryKey(welfareEnterpriseApiOrderSaveDto.getSkuId());
        if(EmptyUtils.isEmpty(welfareGoodsAttr)){
            throw new CommonException(1003,"该款商品已下架01");
        }
        if(welfareGoodsAttr.getStatus()!= CommonConstants.YES){
            throw new CommonException(1003,"该款商品已下架02");
        }
        if(EmptyUtils.isNotEmpty(welfareGoodsAttr.getQuantity()) && welfareEnterpriseApiOrderSaveDto.getNum()>welfareGoodsAttr.getQuantity()){
            throw new CommonException(1004,"库存不够,剩余库存数量:"+welfareGoodsAttr.getQuantity());
        }
        WelfareGoods welfareGoods = welfareGoodsService.selectByPrimaryKey(welfareGoodsAttr.getGoodsId());
        if(EmptyUtils.isEmpty(welfareGoods)){
            throw new CommonException(1003,"该款商品已下架03");
        }
        if(welfareGoods.getGoodsStatus()!= WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode()){
            throw new CommonException(1003,"该款商品已下架04");
        }
        WelfareEnterpriseApiGoods welfareEnterpriseGoodsQuery = new WelfareEnterpriseApiGoods();
        welfareEnterpriseGoodsQuery.setEnterpriseId(welfareEnterpriseApiOrderSaveDto.getEnterpriseId());
        welfareEnterpriseGoodsQuery.setSkuId(welfareEnterpriseApiOrderSaveDto.getSkuId());
        welfareEnterpriseGoodsQuery.setStatus(CommonConstants.YES);
        WelfareEnterpriseApiGoods welfareEnterpriseGoods = mapper.selectOne(welfareEnterpriseGoodsQuery);
        if(EmptyUtils.isEmpty(welfareEnterpriseGoods)){
            throw new CommonException(1003,"该款商品已下架05");
        }
        //根据手机号查询用户是否存在，若不存在则创建一个用户
        WelfareUserWx welfareUserWxQuery = new WelfareUserWx();
        welfareUserWxQuery.setPhone(welfareEnterpriseApiOrderSaveDto.getPhone());
        welfareUserWxQuery.setStatus(CommonConstants.YES);
        welfareUserWxQuery.setEnterpriseId(welfareEnterpriseApiOrderSaveDto.getEnterpriseId());
        List<WelfareUserWx> userWxList = welfareUserWxService.select(welfareUserWxQuery);
        WelfareUserWx welfareUserWx;
        if(EmptyUtils.isNotEmpty(userWxList)){
            welfareUserWx = userWxList.get(0);
        }else{
            welfareUserWx = new WelfareUserWx();
            BeanUtils.copyProperties(welfareEnterpriseApiOrderSaveDto,welfareUserWx);
            welfareUserWx.setUserName(welfareEnterpriseApiOrderSaveDto.getName());
            welfareUserWx.setStatus(CommonConstants.YES);
            welfareUserWx.setIsValid(CommonConstants.YES);
            welfareUserWx.setCreateTime(new Date());
            welfareUserWx.setTotalIntegral(BigDecimal.ZERO);
            welfareUserWx.setBalanceIntegral(BigDecimal.ZERO);
            welfareUserWx.setConsumeIntegral(BigDecimal.ZERO);
            welfareUserWx.setExpiredIntegral(BigDecimal.ZERO);
            welfareUserWx.setDistributeIntegralNum(0);
            welfareUserWxService.insertSelective(welfareUserWx);
        }
        //封装订单对象，只限于包含单个商品
        WelfareOrder welfareOrder = new WelfareOrder();
        welfareOrder.setOrderNo(StringUtil.generateOrderNo());
        welfareOrder.setSupplierId(welfareGoods.getSupplierId());
        welfareOrder.setOrderType(WelfareOrderEnum.ORDER_TYPE_ENTERPRISE_API.getCode());
        welfareOrder.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode());
        //welfareOrder.setApiType(CommonConstants.ORDER_API_TYPE.THIRD_API);//api订单
        welfareOrder.setEnterpriseId(welfareEnterpriseApiOrderSaveDto.getEnterpriseId());
        welfareOrder.setUserId(welfareUserWx.getId());
        welfareOrder.setTotalAmount(welfareEnterpriseGoods.getSupplyPrice().multiply(new BigDecimal(welfareEnterpriseApiOrderSaveDto.getNum())).setScale(2, BigDecimal.ROUND_HALF_UP));
        welfareOrder.setCreditsAmount(BigDecimal.ZERO);
        welfareOrder.setPaymentAmount(welfareOrder.getTotalAmount());
        welfareOrder.setRefundAmount(BigDecimal.ZERO);
        welfareOrder.setRefundPoints(BigDecimal.ZERO);
        welfareOrder.setPayTime(new Date());
        welfareOrder.setCreateTime(new Date());
        welfareOrder.setStatus(CommonConstants.YES);
        StringBuffer orderRemark = new StringBuffer();
        orderRemark.append(welfareEnterpriseApiOrderSaveDto.getGoodsAttrs()+"###");
        if(EmptyUtils.isNotEmpty(welfareEnterpriseApiOrderSaveDto.getRemark())){
            orderRemark.append(welfareEnterpriseApiOrderSaveDto.getRemark());
        }
        welfareOrder.setOrderRemark(orderRemark.toString());
        welfareOrder.setPaymentType(0);
        welfareOrder.setPaymentStatus(WelfareFinanceEnum.FINANCE_PAYMENT_STATUS_NOT_PUSHED.getCode());
        welfareOrderService.insertSelective(welfareOrder);
        //封装订单商品对象
        WelfareOrderGoods welfareOrderGoods = new WelfareOrderGoods();
        BeanUtils.copyProperties(welfareEnterpriseApiOrderSaveDto,welfareOrderGoods);
        BeanUtils.copyProperties(welfareGoodsAttr,welfareOrderGoods);
        welfareOrderGoods.setId(null);
        welfareOrderGoods.setOrderId(welfareOrder.getId());
        welfareOrderGoods.setGoodsQuantity(welfareEnterpriseApiOrderSaveDto.getNum());
        welfareOrderGoods.setStatus(CommonConstants.YES);
        welfareOrderGoods.setGoodsType(WelfareGoodsEnum.GOODS_TYPE_PHYSICAL.getCode());
        welfareOrderGoods.setPartitionId(welfareGoods.getPartitionId());
        welfareOrderGoods.setSupplierId(welfareGoods.getSupplierId());
        welfareOrderGoods.setCostTotalPrice(welfareOrderGoods.getCostPrice().multiply(new BigDecimal(welfareEnterpriseApiOrderSaveDto.getNum())).setScale(2, BigDecimal.ROUND_HALF_UP));
        welfareOrderGoods.setPaymentAmount(welfareEnterpriseGoods.getSupplyPrice());
        welfareOrderGoods.setPaymentCredits(BigDecimal.ZERO);
        welfareOrderGoods.setCreditsAmount(welfareEnterpriseGoods.getSupplyPrice());
        welfareOrderGoods.setCreateTime(new Date());
        welfareOrderGoodsService.insertSelective(welfareOrderGoods);
        //封装订单地址对象
        WelfareOrderAddress welfareOrderAddress = new WelfareOrderAddress();
        BeanUtils.copyProperties(welfareEnterpriseApiOrderSaveDto,welfareOrderAddress);
        welfareOrderAddress.setStatus(CommonConstants.YES);
        welfareOrderAddress.setCreateTime(new Date());
        welfareOrderAddress.setId(null);
        welfareOrderAddressService.insertSelective(welfareOrderAddress);
        //修改订单地址id
        welfareOrder.setAddressId(welfareOrderAddress.getId());
        welfareOrder.setUpdateTime(new Date());
        welfareOrder.setOldId(welfareOrder.getId());
        welfareOrderService.updateByPrimaryKeySelective(welfareOrder);
        //商品库存减少
        welfareGoodsAttr.setQuantity(welfareGoodsAttr.getQuantity()-welfareEnterpriseApiOrderSaveDto.getNum());
        //welfareGoodsAttr.setUpdateTime(new Date());
        welfareGoodsAttrService.updateByPrimaryKeySelective(welfareGoodsAttr);
        //商品销售数量增加
        welfareGoods.setGoodsConvertQuantity(welfareGoods.getGoodsConvertQuantity()+welfareEnterpriseApiOrderSaveDto.getNum());
        //welfareGoods.setUpdateTime(new Date());
        welfareGoodsService.updateByPrimaryKeySelective(welfareGoods);
        return welfareOrder.getId();
    }

    @Override
    public WelfareEnterpriseApiOrderVo getWelfareEnterpriseApiOrderDetail(Integer orderId) {
        WelfareEnterpriseApiOrderVo welfareEnterpriseApiOrderVo = new WelfareEnterpriseApiOrderVo();
        WelfareOrder welfareOrder = welfareOrderService.selectByPrimaryKey(orderId);
        List<WelfareOrderGoodsVo> goodsVos = welfareOrderGoodsService.selectOrderGoodsVoByOrderId(orderId);
        WelfareOrderGoodsVo goodsVo = goodsVos.get(0);
        WelfareOrderAddress welfareOrderAddress = welfareOrderAddressService.selectByPrimaryKey(welfareOrder.getAddressId());
        BeanUtils.copyProperties(welfareOrder,welfareEnterpriseApiOrderVo);
        BeanUtils.copyProperties(goodsVo,welfareEnterpriseApiOrderVo);
        BeanUtils.copyProperties(welfareOrderAddress,welfareEnterpriseApiOrderVo);
        welfareEnterpriseApiOrderVo.setOrderId(orderId);
        //welfareEnterpriseApiOrderVo.setPrice(goodsVo.getPaymentAmount());
        welfareEnterpriseApiOrderVo.setNum(goodsVo.getGoodsQuantity());
        //welfareEnterpriseApiOrderVo.setTotalPrice(welfareOrder.getTotalAmount());
        //welfareEnterpriseApiOrderVo.setGoodsAttrs(welfareOrder.getOrderRemark());
        //welfareEnterpriseApiOrderVo.setRemark(welfareOrder.getRemark());
        String[] orderRemark_ = welfareOrder.getOrderRemark().split("###");
        welfareEnterpriseApiOrderVo.setGoodsAttrs(orderRemark_[0]);
        if(orderRemark_.length==2){
            if(EmptyUtils.isNotEmpty(orderRemark_[1])){
                welfareEnterpriseApiOrderVo.setRemark(orderRemark_[1]);
            }else{
                welfareEnterpriseApiOrderVo.setRemark("");
            }
        }else{
            welfareEnterpriseApiOrderVo.setRemark("");
        }
        if(welfareEnterpriseApiOrderVo.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()){
            welfareEnterpriseApiOrderVo.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
        }
        return welfareEnterpriseApiOrderVo;
    }

    @Override
    public Integer confirmReceiptOrder(Integer orderId, Integer enterpriseId) {
        WelfareOrder welfareOrder = welfareOrderService.selectByPrimaryKey(orderId);
        if(EmptyUtils.isEmpty(welfareOrder)){
            throw new CommonException(1000,"订单id传参有误，该订单不存在");
        }
        if(EmptyUtils.isEmpty(welfareOrder.getOrderType()) || welfareOrder.getOrderType()!=WelfareOrderEnum.ORDER_TYPE_ENTERPRISE_API.getCode()){
            throw new CommonException(1005,"该订单不是api订单");
        }
        if(!welfareOrder.getEnterpriseId().equals(enterpriseId)){
            throw new CommonException(1006,"无权限操作");
        }
        welfareOrder.setId(orderId);
        welfareOrder.setStatus(WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode());
        welfareOrder.setUpdateTime(new Date());
        return welfareOrderService.updateByPrimaryKeySelective(welfareOrder);
    }

    @Override
    public List<WelfareEnterpriseApiOrderExpressVo> getOrderExpressInfo(Integer orderId) {
        List<WelfareOrderExpressVo> welfareOrderExpressVoList = welfareOrderExpressService.getOrderExpressInfo(orderId);
        if(CollectionUtils.isEmpty(welfareOrderExpressVoList)) {
            return new ArrayList<>();
        }
        List<WelfareEnterpriseApiOrderExpressVo> list = new ArrayList<>();
        welfareOrderExpressVoList.forEach(x->{
            WelfareEnterpriseApiOrderExpressVo welfareEnterpriseApiOrderExpressVo = new WelfareEnterpriseApiOrderExpressVo();
            BeanUtils.copyProperties(x,welfareEnterpriseApiOrderExpressVo);
            welfareEnterpriseApiOrderExpressVo.setExpressDetai(x.getExpressList());
            list.add(welfareEnterpriseApiOrderExpressVo);
        });
        return list;
    }

}
